package com.cmcc.groupcontacts.common;

import java.util.ArrayList;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

import com.android.mms.transaction.HttpUtils;
import com.cmcc.groupcontacts.MainApp;
import com.cmcc.groupcontacts.MainApp.AfterBlockedCallbackEvent;
import com.cmcc.groupcontacts.firewall.activity.FirewallConfigModeActivity;
import com.cmcc.groupcontacts.firewall.activity.FirewallTabActivity;
import com.cmcc.groupcontacts.firewall.business.FirewallConfigBusiness;
import com.cmcc.groupcontacts.firewall.business.SmsListBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.KeywordsVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.StringUtil;
import com.google.android.mms.pdu.GenericPdu;
import com.google.android.mms.pdu.PduParser;
import com.yinhai.activity.R;

/**
 * 信息接收器
 * 
 * @author
 * 
 */
public class SmsReceiver extends BaseReceiver {
	private static final String LOG_TAG = "SmsReceiver";

	/** 信息拦截通知ID集合 */
	public static List<Integer> notificationIdList = new ArrayList<Integer>();

	@SuppressWarnings("deprecation")
	@Override
	public void onReceive(Context context, Intent intent) {
		boolean isFirewallOpen = PreferenceManager.getFirewallState();
		// 是否开启拦截功能
		if (isFirewallOpen) {
			String action = intent.getAction();
			if (action.equals(CoreService.SMS_RECEIVED_ACTION)) {
				handleSms(context, intent);
			} else if (action.equals(CoreService.WAP_PUSH_RECEIVED_ACTION)) {
				handleMms(context, intent);
			}
		}
	}

	/*
	 * 处理短信拦截
	 */
	private void handleSms(Context context, Intent intent) {
		try {
			StringBuilder bodyBuilder = new StringBuilder();// 短信内容
			StringBuilder numberBuilder = new StringBuilder();// 短信发件人
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				// 解析信息内容
				Object[] pdus = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++) {
					messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
				for (SmsMessage currentMessage : messages) {
					bodyBuilder.append(currentMessage.getDisplayMessageBody());
					numberBuilder.append(currentMessage
							.getDisplayOriginatingAddress());
				}
				String body = bodyBuilder.toString();
				String number = numberBuilder.toString();
				// 拦截信息
				if (isNeedBlockSms(number, body)) {
					Log.v(LOG_TAG, StringUtil.format("正在拦截信息：(号码){0}，(内容){1}",
							number, body));
					boolean isSuccessful = (new SmsListBusiness()
							.handleBlockedSms(number, body,
									SmsListBusiness.TYPE_SMS) >= 0);
					if (isSuccessful) {
						handler.sendMessage(handler.obtainMessage());
						showSmsNotification(context, number);
						this.abortBroadcast(); // 取消信息广播的传递
					}
				}
			}
		} catch (Exception e) {
			ExceptionHandler.handle(e, "短信拦截处理时出错");
		}
	}

	/*
	 * 处理彩信拦截
	 */
	private void handleMms(Context context, Intent intent) {
		try {
			// 下载彩信内容
			PduParser parser = new PduParser(intent.getByteArrayExtra("data"));
			GenericPdu pdu = parser.parse();
			if (pdu == null) {
				throw new Exception("无法解析彩信头");
			}
			String number = pdu.getFrom().getString();

			// int messageType = pdu.getMessageType();
			// if (messageType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) {
			// NotificationInd nInd = (NotificationInd) pdu;
			// byte[] retrievePduBytes = this.downloadMms(context, new
			// String(nInd.getContentLocation()));
			// if (retrievePduBytes == null) {
			// throw new Exception("无法下载彩信内容");
			// }
			// // 解析彩信内容
			// parser = new PduParser(retrievePduBytes);
			// GenericPdu retrievePdu = parser.parse();
			// if (retrievePdu == null) {
			// throw new Exception("无法解析彩信内容");
			// }
			// messageType = retrievePdu.getMessageType();
			// if (messageType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) {
			// RetrieveConf conf = (RetrieveConf) retrievePdu;
			// String number = conf.getFrom().getString();
			// String body = conf.getSubject().getString();

			// 拦截彩信
			if (isNeedBlockSms(number, "")) {
				Log.v(LOG_TAG, StringUtil.format("正在拦截彩信：(号码){0}", number));
				boolean isSuccessful = (new SmsListBusiness().handleBlockedSms(
						number, "[彩信]", SmsListBusiness.TYPE_MMS) >= 0);
				if (isSuccessful) {
					handler.sendMessage(handler.obtainMessage());
					showSmsNotification(context, number);
					this.abortBroadcast(); // 取消信息广播的传递
				}
			}
			// }
			// }
		} catch (Exception e) {
			ExceptionHandler.handle(e, "彩信拦截处理时出错");
		}
	}

	private byte[] pduBytes = null;
	private boolean isDownloaded = false;

	/*
	 * 下载彩信（仅支持移动彩信下载）
	 */
	private byte[] downloadMms(final Context context, final String url) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				pduBytes = getMms(context, url);
				isDownloaded = true;
			}

			private byte[] getMms(final Context context, final String url) {
				try {
					if (!beginMmsConnectivity(context)) {
						throw new Exception("无法启动彩信CMWAP连接");
					}

					try {
						byte[] pduBytes = HttpUtils.httpConnection(context,
								-1L, url, null, HttpUtils.HTTP_GET_METHOD,
								true, "10.0.0.172", 80);
						return pduBytes;
					} finally {
						endMmsConnectivity(context);
					}
				} catch (Exception e) {
					ExceptionHandler.handle(e, "彩信下载时出错");
					return null;
				}
			}
		}).start();

		while (true) {
			if (isDownloaded) {
				isDownloaded = false;
				return pduBytes;
			} else {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	private boolean beginMmsConnectivity(final Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		new Thread(new Runnable() {
			@Override
			public void run() {
				connMgr.startUsingNetworkFeature(
						ConnectivityManager.TYPE_MOBILE, "enableMMS");
			}
		}).start();

		while (true) {
			if (connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS)
					.getState() == NetworkInfo.State.CONNECTED) {
				return true;
			} else {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	private void endMmsConnectivity(Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		new Thread(new Runnable() {
			@Override
			public void run() {
				connMgr.stopUsingNetworkFeature(
						ConnectivityManager.TYPE_MOBILE, "enableMMS");
			}
		}).start();
	}

	/*
	 * 校验是否需要拦截信息
	 */
	private boolean isNeedBlockSms(String number, String body) {
		boolean isNeedBlockSms = false;
		switch (PreferenceManager.getFirewallMode()) {
		case FirewallConfigModeActivity.MODE_STANDARD: // 智能拦截
		case FirewallConfigModeActivity.MODE_BLOCK_BLACK: // 只拦截黑名单
			isNeedBlockSms = isExistedInBlackList(number);
			break;
		case FirewallConfigModeActivity.MODE_PASS_WHITE: // 只放行白名单
			isNeedBlockSms = !isExistedInWhiteList(number);
			break;
		case FirewallConfigModeActivity.MODE_PASS_LOCAL_CONTACTS: // 只放行本地通信录
			isNeedBlockSms = !isExistedInLocalContacts(number);
			break;
		case FirewallConfigModeActivity.MODE_PASS_ALL_CONTACTS: // 只放行本地和集团通信录
			isNeedBlockSms = (!isExistedInLocalContacts(number) && !isExistedInAllContacts(number));
			break;
		case FirewallConfigModeActivity.MODE_BLOCK_ALL: // 全部拦截
			isNeedBlockSms = true;
			break;
		case FirewallConfigModeActivity.MODE_CUSTOMIZE: // 自定义拦截规则
			boolean isBlockBlackList = PreferenceManager.getFirewallModeState(
					PreferenceManager.CONFIG_FIREWALL_MODE_BLACK, true);
			if (isBlockBlackList) {
				// 拦截黑名单
				if (isExistedInBlackList(number)) {
					isNeedBlockSms = true;
					break;
				}
			}
			boolean isPassWhiteList = PreferenceManager.getFirewallModeState(
					PreferenceManager.CONFIG_FIREWALL_MODE_WHITE, true);
			if (isPassWhiteList) {
				// 放行白名单
				if (isExistedInWhiteList(number)) {
					isNeedBlockSms = false;
					break;
				}
			}
			boolean isPassLocalContactsSms = !PreferenceManager
					.getFirewallModeState(
							PreferenceManager.CONFIG_FIREWALL_MODE_LOCAL_CONTACTS_SMS,
							false);
			if (isPassLocalContactsSms) {
				// 在本地通信录中存在则放行
				if (isExistedInLocalContacts(number)) {
					isNeedBlockSms = false;
					break;
				}
			} else {
				// 在本地通信录中存在则拦截
				if (isExistedInLocalContacts(number)) {
					isNeedBlockSms = true;
					break;
				}
			}
			boolean isPassGroupContactsSms = !PreferenceManager
					.getFirewallModeState(
							PreferenceManager.CONFIG_FIREWALL_MODE_GROUP_CONTACTS_SMS,
							false);
			if (isPassGroupContactsSms) {
				// 在集团通信录中存在则放行
				if (!isExistedInLocalContacts(number)
						&& isExistedInAllContacts(number)) {
					isNeedBlockSms = false;
					break;
				}
			} else {
				// 在集团通信录中存在则拦截
				if (!isExistedInLocalContacts(number)
						&& isExistedInAllContacts(number)) {
					isNeedBlockSms = true;
					break;
				}
			}
			break;
		}

		if (!isNeedBlockSms) { // 到这里都还不需要拦截的话，完成剩余的校验
			switch (PreferenceManager.getFirewallMode()) {
			case FirewallConfigModeActivity.MODE_STANDARD: // 智能拦截
				// 校验拦截关键字
				isNeedBlockSms = isContainKeywords(body, isNeedBlockSms);
				break;
			case FirewallConfigModeActivity.MODE_CUSTOMIZE: // 自定义拦截规则
				boolean isPassStrangerSms = !PreferenceManager
						.getFirewallModeState(
								PreferenceManager.CONFIG_FIREWALL_MODE_STRANGER_SMS,
								false);
				if (isPassStrangerSms) {
					// 放行陌生人
					isNeedBlockSms = false;
				} else {
					// 智能拦截陌生人：校验拦截关键字
					isNeedBlockSms = isContainKeywords(body, isNeedBlockSms);
				}
				break;
			}
		}
		return isNeedBlockSms;
	}

	/*
	 * 校验是否包含拦截关键字
	 */
	private boolean isContainKeywords(String body, boolean isNeedBlockSms) {
		ArrayList<KeywordsVO> keywordsList = new FirewallConfigBusiness()
				.getKeywordsList();
		for (KeywordsVO keywords : keywordsList) {
			if (body.contains(keywords.getKeywords())) {
				isNeedBlockSms = true;
				break;
			}
		}
		return isNeedBlockSms;
	}

	/*
	 * 显示信息拦截系统栏通知
	 */
	private void showSmsNotification(Context context, String number) {
		// TODO: [优化]合并多条提醒
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.sty2_prompt,
				"集团通信录信息拦截通知", System.currentTimeMillis());
		// TODO: 拦截提示音
		notification.defaults = Notification.DEFAULT_SOUND;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent notificationIntent = new Intent(context,
				FirewallTabActivity.class);
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		notificationIntent.putExtra(FirewallTabActivity.TAB_INDEX, 0);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context, "集团通信录提醒", "已拦截" + number
				+ "的信息", pendingIntent);
		int notificationId = CoreService.notificationIdCounter++;
		notificationIdList.add(notificationId);
		notificationManager.notify(notificationId, notification);
	}

	private static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			for (AfterBlockedCallbackEvent callback : MainApp
					.getSmsCallbackEvents()) {
				callback.invoke(msg);
			}
		};
	};
}
